<template>
  <div class="form-content">
    <div class="title">
      新建病例
    </div>
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" :inline="false">
      <!-- 循环渲染表单项 -->
      <el-form-item v-for="(item, index) in formItems" :key="index" :label="item.label">
        <!-- 根据不同的类型渲染不同的表单元素 -->
        <template v-if="item.type === 'input'">
          <el-input v-model="formData[item.prop]" :placeholder="item.placeholder" class="single-min-input" />
        </template>
        <template v-else-if="item.type === 'select'">
          <el-select v-model="formData[item.prop]" :placeholder="item.placeholder" class="single-min-input">
            <el-option v-for="option in item.options" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </template>
        <template v-else-if="item.type === 'textarea'">
          <el-input v-model="formData[item.prop]" type="textarea" :placeholder="item.placeholder" class="single-common-input"/>
        </template>
      </el-form-item>
    </el-form>
    <div class="bottom-btn">
      <!-- 操作按钮 -->
      <el-button type="primary" @click="handleSubmit">提交</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'MyForm',
  props: {
    // 表单数据
    initialFormData: {
      type: Object,
      default: () => ({})
    },
    // 表单验证规则
    formRules: {
      type: Object,
      default: () => ({})
    },
    // 表单项配置
    formItems: {
      type: Array,
      default: () => []
    },
    // label的宽度
    labelWidth: {
      type: String,
      default: '100px'
    }
  },
  data() {
    return {
      formData: { ...this.initialFormData },
      formRef: null
    }
  },
  methods: {
    // 提交表单
    handleSubmit() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          // 验证通过，触发自定义事件将表单数据传递给父组件
          this.$emit('submit', this.formData)
        } else {
          console.log('表单验证失败')
          return false
        }
      })
    },
    // 重置表单
    handleReset() {
      this.$refs.formRef.resetFields()
      this.formData = { ...this.initialFormData }
    }
  }
}
</script>

<style lang="scss" scoped>
  .form-content{
    display: flex;
        flex-direction: column;
        height: calc(100vh - 50px);
        padding: 15px 20px;
        background-color: #f7f8f9;
  }
  .title{
    color: #666666;
    margin-bottom: 20px;
  }
  .single-min-input{
    width: 220px !important;
  }
  .single-common-input{
    width: 440px !important;
  }
  .bottom-btn{
    display: flex;
    justify-content: center;
  }
</style>
